package com.shwread.android.ui.customview;

import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.shwread.android.qysw10000204.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.EBannerInfo;
import logic.constants.DefaultConsts;
import logic.util.PicassoUtil;


public class OrderIndexViewPagerAdapter
        extends
        PagerAdapter
{
	
	private Activity                        activity;
	private List<EBannerInfo>               bannerList = new ArrayList<EBannerInfo>();
	private HashMap<Integer, View>          views;
	private OrderIndexBannerOnClickListener listener;
	private int                             size = 0;
	
	public OrderIndexViewPagerAdapter(Activity activity, /*
														  * List<BannerInfo>
														  * bannerList,
														  */HashMap<Integer, View> views, OrderIndexBannerOnClickListener bannerOnClickListener) {
		this.activity = activity;
		//		this.bannerList = bannerList;
		this.views = views;
		this.listener = bannerOnClickListener;
		//		this.size = bannerList.size();
	}
	
	public void setData(List<EBannerInfo> bannerList) {
		this.bannerList = bannerList;
		this.size = bannerList.size();
		notifyDataSetChanged();
	}
	
	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}
	
	@Override
	public int getCount() {
		return size;
	}
	
	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}
	
	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		View view = views.get(position);
		if (view == null)
		{
			view = activity.getLayoutInflater().inflate(R.layout.banner_item, null);
			ImageView img = (ImageView) view.findViewById(R.id.banner_item_image);
			final EBannerInfo bannerInfo = bannerList.get(position);
			
//			img.setImageUrl(appendBannerUrl(bannerInfo.getPicUrl()), R.drawable.bg_big_image, R.drawable.bg_big_image);
			PicassoUtil.load(activity, appendBannerUrl(bannerInfo.getPicUrl()), R.drawable.bg_big_image, img);

			view.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v) {
					listener.click(bannerInfo);
				}
			});
			views.put(position, view);
		}
		if (view.getParent() != null)
		{
			container.removeView(view);
		}
		container.addView(view);
		return view;
	}
	
	//imgUrl +  ?c=0&w=120&h=230&p=0
	private String appendBannerUrl(String imgUrl) {
		StringBuffer sb = new StringBuffer(imgUrl);
		sb.append("?c=0&w=");
		sb.append(DefaultConsts.BANNER_DEFAULT_WIDTH);
		sb.append("&h=");
		sb.append(DefaultConsts.BANNER_DEFAULT_HIGHT);
		sb.append("&p=0");
		return sb.toString();
	}
	
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView(views.get(position));
	}
	
}
